package cz.cvut.fit.web.nakupniSeznam.dao;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import cz.cvut.fit.web.nakupniSeznam.data.Category;
import cz.cvut.fit.web.nakupniSeznam.data.List;
import cz.cvut.fit.web.nakupniSeznam.data.Unit;
import cz.cvut.fit.web.nakupniSeznam.data.User;

public class UserDAO extends GenericDAO<User> {
	
	public static final String REMOVED_FROM_LIST = "removing complete";

	private static UserDAO instance = null;

	public static UserDAO getInstance() {
		if (instance == null) {
			instance = new UserDAO();
		}
		return instance;
	}

	@Override
	protected String getAllQueryName() {
		return "user.getAll";
	}

	@Override
	protected Class<User> getEntityClass() {
		return User.class;
	}

	@Override
	public void remove(Long id) {

		// remove all user's owned lists
		java.util.List<List> listOfOwnedLists = ListDAO.getInstance()
				.getByOwner(this.getById(id).getKey());
		for (List l : listOfOwnedLists) {
			ListDAO.getInstance().remove(l.getId());
		}

		// remove all owned categories
		java.util.List<Category> listOfOwnedCategories = CategoryDAO
				.getInstance().getByOwner(this.getById(id).getKey());
		for (Category c : listOfOwnedCategories) {
			CategoryDAO.getInstance().remove(c.getId());
		}

		// remove all owned categories
		java.util.List<Unit> listOfOwnedUnits = UnitDAO.getInstance()
				.getByOwner(this.getById(id).getKey());
		for (Unit unit : listOfOwnedUnits) {
			UnitDAO.getInstance().remove(unit.getId());
		}
		super.remove(id);
	}

	public User getByKey(String key) {
		Query q = this.em.createNamedQuery("user.getByKey");
		q.setParameter("key", key);

		try {
			return (User) q.getSingleResult();
		} catch (NoResultException ex) {
			return null;
		}
	}

	public void changeKey(String oldKey, String newKey) {
		User u = this.getByKey(oldKey);

		// change key in all owned lists
		java.util.List<List> listOfOwnedLists = ListDAO.getInstance()
				.getByOwner(oldKey);
		for (List l : listOfOwnedLists) {
			l.setOwner(newKey);
			ListDAO.getInstance().save(l);
		}

		// change in all owned categories
		java.util.List<Category> listOfOwnedCategories = CategoryDAO
				.getInstance().getByOwner(oldKey);
		for (Category c : listOfOwnedCategories) {
			c.setOwner(newKey);
			CategoryDAO.getInstance().save(c);
		}

		// change in all owned categories
		java.util.List<Unit> listOfOwnedUnits = UnitDAO.getInstance()
				.getByOwner(oldKey);
		for (Unit unit : listOfOwnedUnits) {
			unit.setOwner(newKey);
			UnitDAO.getInstance().save(unit);
		}

		u.setKey(newKey);
		this.save(u);
	}
}